import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ParkDataProvider } from '../../providers/park-data/park-data';
import { Park } from '../../providers/park-data/park';
import { ParkDetailPage } from '../park-detail/park-detail';
import * as _ from "lodash";
//声明高德地图对象AMap
declare var AMap:any;
/**
 * Generated class for the ParkMapPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-park-map',
  templateUrl: 'park-map.html',
})
export class ParkMapPage {
@ViewChild('map_container')map_container:ElementRef;

  private map:any;
  private parks:Park[]=[];
  private markers:any[]=[];

  constructor(public navCtrl: NavController,
     public navParams: NavParams,
     public parkDataProvider:ParkDataProvider) {
  }

  ionViewDidLoad() {
    this.setData();
   this.initAMap();
   //this.setMarker();
   this.setEvent();
  
  }

  initAMap(){
   this.map = new AMap.Map(this.map_container.nativeElement, {
     resizeEnable:true,
      zoom:11,//级别
      //center: [116.397428, 39.90923],//中心点坐标 
  });
  //加载插件
  AMap.plugin(['AMap.ToolBar','AMap.Geolocation','AMap.Autocomplete','AMap.PlaceSearch'],()=>{
    this.map.addControl(new AMap.ToolBar());
    let geolocation=new AMap.Geolocation();
    geolocation.getCurrentPosition((status,result)=>{
      console.log(`精确定位：${status}`);
      console.log(result);
    });
    geolocation.getCityInfo((status,result)=>{
      console.log(`城市定位：${status}`);
      console.log(result);
    });
    this.map.addControl(geolocation);
    let auto=new AMap.Autocomplete({
      input:'tipinput',
      type:'190101|190102|190103|190104|190105|190106|190200|190201|190202|190203|190204|190205|'
    });
    this.map.addControl(auto);
    let placeSearch =new AMap.PlaceSearch({map:this.map});
    this.map.addControl(placeSearch);
    auto.on('select',event=>{
      placeSearch.setCity(event.poi.adcode);
      placeSearch.search(event.poi.name,(status,result)=>{
        this.map.clearMap();
        this.setData();
      });
    });
  });
  }
  setMarker(parks:Park[]){
    // parks=parks.slice(0,10);
    // console.log(parks);
    parks.forEach(park=>{
      let [lng,lat]=park.point.split(',');
    let marker=new AMap.Marker({
      position:new AMap.LngLat(lng,lat),
      title:park.name,
      label:{content:park.name,offset:new AMap.Pixel(20,-10)},clickable:true
    });
    marker.on('click',event=>{
      console.log(`点击经纬度为：[${event.lnglat.getLat()},${event.lnglat.getLng()}]`);
      this.parkDataProvider.getPark(park.objectId).subscribe(park=>{
        this.navCtrl.push(ParkDetailPage,{park:park});
      }); 
    });
    this.markers.push(marker);
  });
    this.map.add(this.markers);
  }

  setData(){
    this.parks=[];
  //   this.parkDataProvider.getCount().toPromise()
  //   .then(total=>{console.log(`记录数：${total}`);
  //   return this.parkDataProvider.getAllParks(total).toPromise();
  // })

  // .then(data=>{
  //   data.forEach(_parks=>{
  //     this.parks=this.parks.concat(_parks);
  //   });
  //   console.log(`Parks集合大小：${this.parks.length}`);
  // })

  this.parkDataProvider.getParksFromCache()
  .then(res=>{
    if(res&&res.rows && res.rows.length>0){
      console.log(`查询结果集：${res.rows.length}`);
      for(let i=0;i<res.rows.length;i++){
        this.parks.push({
          objectId:res.rows.item(i).objectId,
          name:res.rows.item(i).name,
          point:res.rows.item(i).point
        } as Park);
      }
    }
  })
  .then(()=>{
    this.parks=_.filter(this.parks,(park:Park)=>{
      let [lng,lat]=park.point.split(',');
      let _point=new AMap.LngLat(lng,lat);
      if(this.map.getBounds().contains(_point))
      return true;
    });
    console.log(`当前可视区域内的景区数：${this.parks.length}`);
  })
  .then(()=>{
    this.setMarker(this.parks);
  });
  }
/**
 * 移动缩放时重新获取景点信息
 */
  setEvent(){
    this.map.on('moveend',()=>{this.setData();});
    this.map.on('zoomend',()=>{this.setData();});
  }
}
